<template>
  <div>
    <!-- 面包屑导航 -->
    <tab-control  :title="['首页','用户管理','用户列表']"></tab-control>

    <!-- 卡片视图 -->
    <el-card class="box-card">
      <!-- 搜索与添加用户 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <!-- 搜索区域 -->
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <!-- 用户列表 -->
      <el-table :data="userLise" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态" prop="mg_state">
          <template v-slot="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template v-slot="scope">
            <!-- 修改 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="edit(scope.row.id)"
            ></el-button>

            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="remove(scope.row.id)"
            ></el-button>

            <!-- 分配角色 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addCloseDialog"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editVisible"
      width="50%"
      @close="editCloseDialog"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配对话框 -->
    <el-dialog title="提示" :visible.sync="setRolesDialog" width="50%" @close="resetRole">
      <div>
        <p>当前用户:{{ userInfo.username }}</p>
        <p>当前角色:{{ userInfo.role_name }}</p>
        <p>
          分配新角色:
          <el-select v-model="selectRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRolesDialog = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getUserList,
  userStateChange,
  addUser,
  editUser,
  getUser,
  remove,
  setRole,
  saveRoleInfo
} from "@/api/utils";
import TabControl from '@/components/tabcontrol/TabControl.vue'
export default {
  name: "Users",
  components:{
    TabControl
  },
  data() {
    // 验证邮箱
    var checkemail = (rule, value, cb) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (regEmail.test(value)) {
        return cb();
      } else {
        cb(new Error("请输入合法邮箱"));
      }
    };
    // 验证手机
    var checkphone = (rule, value, cb) => {
      const regPhone =
        /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regPhone.test(value)) {
        return cb();
      } else {
        cb(new Error("请输入合法手机号"));
      }
    };
    return {
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      userLise: [],
      total: 0,
      // 添加对话框隐藏显示
      addDialogVisible: false,
      // 修改对话框隐藏显示
      editVisible: false,
      // 表单数据
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      editForm: {},
      // 添加表单验证规则对象
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "用户名长度在 3 到 10 字符之间",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "用户名长度在 6 到 15 字符之间",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkemail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          { validator: checkphone, trigger: "blur" },
        ],
      },
      // 修改表单验证规则对象
      editFormRules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkemail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          { validator: checkphone, trigger: "blur" },
        ],
      },
      setRolesDialog: false,
      userInfo: {},
      rolesList: [],
      selectRoleId:''
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    getUserList() {
      getUserList(
        this.queryInfo.query,
        this.queryInfo.pagenum,
        this.queryInfo.pagesize
      ).then((res) => {
        // console.log(res);
        if (res.meta.status != 200)
          return this.$message.error("获取用户列表失败!");
        this.userLise = res.data.users;
        this.total = res.data.total;
      });
    },

    // 监听pagesize改变 一页pagesize条数据
    handleSizeChange(newpage) {
      // console.log(newpage);
      this.queryInfo.pagesize = newpage;
      this.getUserList();
    },

    // 监听页码值改变
    handleCurrentChange(newpage) {
      // console.log(newpage);
      this.queryInfo.pagenum = newpage;
      this.getUserList();
    },

    // 状态改变
    userStateChange(userinfo) {
      // console.log(userinfo);
      userStateChange(userinfo.id, userinfo.mg_state).then((res) => {
        // console.log(res);
        if (res.meta.status != 200) {
          userinfo.mg_state = !userinfo.mg_state;
          return this.$message.error("更新用户状态失败!");
        }
      });
    },

    // 重置
    addCloseDialog() {
      this.$refs.addFormRef.resetFields();
    },

    // 重置
    editCloseDialog() {
      this.$refs.editFormRef.resetFields();
    },

    // 添加用户
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        addUser(this.addForm).then((res) => {
          console.log(res);
          if (res.meta.status != 201) {
            this.$message.error("添加用户失败!");
          } else {
            this.$message.success("添加用户成功!");
            this.addDialogVisible = false;
            this.getUserList();
          }
        });
      });
    },

    // 编辑用户信息
    edit(id) {
      getUser(id).then((res) => {
        console.log(res);
        if (res.meta.status != 200)
          return this.$message.error("查询用户信息失败!");
        this.editForm = res.data;
        this.editVisible = true;
      });
    },

    // 修改用户信息
    editUserInfo() {
      this.$refs.editFormRef.validate((valid) => {
        // console.log(valid);
        if (!valid) return;
        editUser(
          this.editForm.id,
          this.editForm.email,
          this.editForm.mobile
        ).then((res) => {
          // console.log(res);
          if (res.meta.status != 200)
            return this.$message.error("更新用户失败!");
          this.editVisible = false;
          this.getUserList();
          this.$message.success("更新用户成功!");
        });
      });
    },

    // 删除用户
    remove(id) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          remove(id).then((res) => {
            // console.log(res);
            if (res.meta.status != 200)
              return this.$message.error("删除用户失败!");
            this.$message.success("删除用户成功!");
            this.getUserList();
          });
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },

    // 分配角色对话框
    setRole(userInfo) {
      this.userInfo = userInfo;
      this.setRolesDialog = true;
      setRole().then((res) => {
        // console.log(res);
        if (res.meta.status != 200)
          return this.$message.error("获取角色列表失败!");
        this.rolesList = res.data;
      });
    },

    //选择角色
    saveRoleInfo(){
      if(!this.selectRoleId) return this.$message.error("请选择要分配的角色!")
      saveRoleInfo(this.userInfo.id,this.selectRoleId).then(res=>{
        console.log(res);
        if(res.meta.status!=200)return this.$message.error("分配的角色失败!")
        this.$message.success("分配角色成功!")
        this.getUserList()
        this.setRolesDialog=false
      })
    },
    resetRole(){
      this.selectRoleId=''
      this.userInfo=''
    }
  },
};
</script>

<style lang="less" scoped>
</style>